﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml.Serialization;

namespace Seagull.Model.Sms
{
    [DebuggerDisplay("{ToString()}")]
    public class SmsMessage
    {
        public const int MaxLengthPerMessage = 60;

        public List<string> Recipients { get; set; }

        private string _content;
        public string Content
        {
            get { return _content; }
            set
            {
                if(string.IsNullOrWhiteSpace(value))
                {
                    throw new ArgumentException("Empty SMS message content.", "value");
                }
                _content = value;
            }
        }

        [XmlIgnore]
        public IEnumerable<string> ContentParts
        {
            get
            {
                if(Content.Length <= MaxLengthPerMessage)
                {
                    yield return Content;
                }
                else
                {
                    var parts = Split(_content, MaxLengthPerMessage - 7).ToArray();
                    for(int i = 0; i < parts.Length; i++)
                    {
                        yield return string.Format("({0}/{1}){2}", i + 1, parts.Length, parts[i]);
                    }
                }
            }
        }

        public SmsMessage()
        {
        }

        public SmsMessage(string content, IEnumerable<string> recipients)
        {
            _content = content;
            Recipients = recipients.ToList();
        }

        internal static IEnumerable<string> Split(string str, int chunkSize)
        {
            for(var pos = 0; pos < str.Length; pos += chunkSize)
            {
                if(pos + chunkSize > str.Length)
                    chunkSize = str.Length - pos;
                yield return (str.Substring(pos, chunkSize));
            }
        }

        public override string ToString()
        {
            return string.Format("Recipients: {0}, Content: {1}", string.Join(",", Recipients), _content);
        }
    }
}
